package com.msb.mall.mallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

@Component
@Slf4j
public class ElasticsearchIndexChecker implements CommandLineRunner {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void run(String... args) throws Exception {
        String indexName = "mall_product";

        // 检查索引是否存在
        // 检查索引是否存在
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (exists) {
            System.out.println("索引 " + indexName + " 已存在");
        } else {
            System.out.println("索引 " + indexName + " 不存在,开始创建索引");

            // 读取 resources 下的 JSON 文件内容
            String jsonStr = readFile2Str("product-mapping-new.json");
            System.out.println(jsonStr);
            ;
            // 创建索引
            Request createRequest = new Request("PUT", "/" + indexName);
            createRequest.setJsonEntity(jsonStr);
            Response createResponse = client.getLowLevelClient().performRequest(createRequest);

            if (createResponse.getStatusLine().getStatusCode() == 200) {
                System.out.println("索引 " + indexName + " 创建成功");
            } else {
                System.out.println("索引 " + indexName + " 创建失败");
            }
        }
    }

    /**
     * 读取文件内容到字符串
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    private String readFile2Str(String filePath) throws Exception {

        // 加载资源文件
        ClassPathResource resource = new ClassPathResource(filePath);
        StringBuilder contentBuilder = new StringBuilder();

        // 逐行读取文件内容
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                //line是# 开头的行，跳过
                if (line.startsWith("#")) {
                    continue;
                }
                contentBuilder.append(line).append("\n");
            }
        }
        return contentBuilder.toString();

    }
}
